let express = require('express');
let router = express.Router();
var fs = require("fs");

router.get('/', function (req, res, next) {
    let params = req.query;
    if (params.tableName === undefined || params.tableName === "") {
        res.json({"success": false, "message": "表名不能为空！"});
        return;
    }

    req.app.db.query("SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE table_schema = ? and table_name = ?", [global.db.database, params.tableName], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "表名不存在！"});
            return;
        }

        let cName = results[0].TABLE_COMMENT;

        req.app.db.query("select * from information_schema.columns where table_schema = ? and table_name = ?", [global.db.database, params.tableName], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            let data = writeData(params.tableName, cName, results);

            fs.writeFile(params.tableName + "s.js", data, function (err) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                res.json({"success": true, "message": "代码生成成功！"});
            });
        });
    });
});

function writeData(tableName, cName, columns) {
    let data = `
let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');
    `;

    data += writeSearchList(tableName, cName, columns);
    data += writeSearchSingle(tableName, cName);
    data += writeUpdate(tableName, cName, columns);
    data += writeInsert(tableName, cName, columns);
    data += writeDelete(tableName, cName);

    data += `
module.exports = router;
    `;

    return data;
}

/**
 * 生成查询全部数据 by v 2018-10-15
 *
 *
 *
 */
function writeSearchList(tableName, cName, columns) {
    let now = new Date().Format("yyyy-MM-dd");
    let data = `
/**
 * 查询${cName}数据 ${now}
 *
 * 按条件查询${cName}数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];

    req.app.db.query("select count(1) as totalCount from ${tableName} " + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from ${tableName} " + sql + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }
            
            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});
`;

    return data;
}

/**
 * 生成查询单一数据 by v 2018-10-15
 *
 *
 *
 */
function writeSearchSingle(tableName, cName) {
    let now = new Date().Format("yyyy-MM-dd");
    let data = `
/**
 * 查看${cName}数据 ${now}
 *
 * 按id查看指定的${cName}信息
 *
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select * from ${tableName} where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});
`;

    return data;
}

/**
 * 生成修改数据 by v 2018-10-15
 *
 *
 *
 */
function writeUpdate(tableName, cName, columns) {
    let now = new Date().Format("yyyy-MM-dd");
    let data = `
/**
 * 修改${cName}数据 ${now}
 *
 *
 */
router.put('/:id', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let now = new Date();

`;
    let datas = [];
    data += requirePrimaryKey(cName, columns);
    data += requireNotNull(cName, columns);
    let sql = splicingNotPrimaryKeyForUpdate(columns, datas);
    let wsql = splicingPrimaryKeyForUpdate(columns, datas);

    data += `    
    req.app.db.query("update ${tableName} set ${sql}${wsql}", [${datas.join(", ")}], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.putMsg});
    });
});
`;
    return data;
}

/**
 * 生成新增数据 by v 2018-10-15
 *
 *
 *
 */
function writeInsert(tableName, cName, columns) {
    let now = new Date().Format("yyyy-MM-dd");
    let data = `
/**
 * 新增${cName}数据 ${now}
 *
 *
 */
router.post('/', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let now = new Date();
    `;

    let datas = [];
    data += requireNotNull(cName, columns);
    let sql = splicingNotPrimaryKeyForInsert(columns, datas);
    var params = "";
    datas.forEach(function() {
        params += (params === "" ? "" : ", ") + "?";
    });

    data += `
    req.app.db.query("insert into ${tableName}(${sql}) values(${params})", [${datas.join(", ")}], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.postMsg});
    });
});
    `;

    return data;
}

/**
 * 生成删除数据 by v 2018-10-15
 *
 *
 *
 */
function writeDelete(tableName, cName) {
    let now = new Date().Format("yyyy-MM-dd");
    let data = `
/**
 * 删除${cName}信息 ${now}
 *
 * 按id删除指定的${cName}信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query('delete from ${tableName} where id = ?', [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.deleteMsg});
    });
});
    `;

    return data;
}

function requirePrimaryKey(cName, columns) {
    let data = "";
    columns.forEach(function(item) {
        if (item.COLUMN_KEY === 'PRI') {
            data += `    
    if (params.${item.COLUMN_NAME} === undefined || params.${item.COLUMN_NAME} === '') {
        res.json({"success": false, "message": "${cName}${item.COLUMN_COMMENT}错误！"});
        return;
    }
` ;
        }
    });

    return data;
}

function requireNotNull(cName, columns) {
    let data = "";
    columns.forEach(function(item) {
        if (item.COLUMN_KEY !== 'PRI' && item.IS_NULLABLE === 'NO') {
            if (item.DATA_TYPE === 'int' || item.DATA_TYPE === 'float' || item.DATA_TYPE === 'double') {
                data += `    
    let ${item.COLUMN_NAME} = 0;    
    if (params.${item.COLUMN_NAME} !== undefined && params.${item.COLUMN_NAME} !== "") {
        ${item.COLUMN_NAME} = params.${item.COLUMN_NAME};
    }
`;
            }
            else if (item.DATA_TYPE === 'varchar' || item.DATA_TYPE === 'char' || item.DATA_TYPE === 'text' || item.DATA_TYPE === 'datetime') {
                data += `    
    if (params.${item.COLUMN_NAME} === undefined || params.${item.COLUMN_NAME} === '' ) {
        res.json({"success": false, "message": "${cName}${item.COLUMN_COMMENT}不能为空！"});
        return;
    }
`;
            }
        }
    });

    return data;
}

function splicingNotPrimaryKeyForUpdate(columns, datas) {
    let sql = "";
    columns.forEach(function(item) {
        if (item.COLUMN_KEY !== 'PRI') {
            let isUpdate = true;
            if (item.COLUMN_NAME === "userId") {
                datas.push("user.id");
            }
            else if (item.COLUMN_NAME === "userName") {
                datas.push("user.trueName");
            }
            else if (item.COLUMN_NAME === "createDate") {
                isUpdate = false;
            }
            else if (item.COLUMN_NAME === "updateDate") {
                datas.push("now");
            }
            else {
                if (item.DATA_TYPE === 'int' || item.DATA_TYPE === 'float' || item.DATA_TYPE === 'double') {
                    datas.push(item.COLUMN_NAME);
                }
                else if (item.DATA_TYPE === 'varchar' || item.DATA_TYPE === 'char' || item.DATA_TYPE === 'text' || item.DATA_TYPE === 'datetime') {
                    datas.push("params." + item.COLUMN_NAME);
                }
            }

            if (isUpdate) {
                if (sql === "") {
                    sql += item.COLUMN_NAME + " = ?";
                }
                else {
                    sql += ", " + item.COLUMN_NAME + " = ?";
                }
            }
        }
    });

    return sql;
}

function splicingPrimaryKeyForUpdate(columns, datas) {
    let wsql = "";
    columns.forEach(function(item) {
        if (item.COLUMN_KEY === 'PRI') {
            if (wsql === "") {
                wsql = " where " + item.COLUMN_NAME + " = ?";
            }
            else {
                wsql += " and " + item.COLUMN_NAME + " = ?";
            }

            datas.push("params." + item.COLUMN_NAME);
        }
    });

    return wsql;
}

function splicingNotPrimaryKeyForInsert(columns, datas) {
    let sql = "";
    columns.forEach(function(item) {
        if (item.COLUMN_KEY !== 'PRI') {
            if (item.COLUMN_NAME === "userId") {
                datas.push("user.id");
            }
            else if (item.COLUMN_NAME === "userName") {
                datas.push("user.trueName");
            }
            else if (item.COLUMN_NAME === "createDate") {
                datas.push("now");
            }
            else if (item.COLUMN_NAME === "updateDate") {
                datas.push("now");
            }
            else {
                if (item.DATA_TYPE === 'int' || item.DATA_TYPE === 'float' || item.DATA_TYPE === 'double') {
                    datas.push(item.COLUMN_NAME);
                }
                else if (item.DATA_TYPE === 'varchar' || item.DATA_TYPE === 'char' || item.DATA_TYPE === 'text' || item.DATA_TYPE === 'datetime') {
                    datas.push("params." + item.COLUMN_NAME);
                }
            }

            if (sql === "") {
                sql += item.COLUMN_NAME;
            }
            else {
                sql += ", " + item.COLUMN_NAME;
            }
        }
    });

    return sql;
}

module.exports = router;